use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::checkout::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub customer_id: String,
    pub guest_id: String,
    pub shipping_address_id: String,
    pub shipping_method_code: String,
    pub billing_address_id: String,
    pub billing_method_code: String,
    pub comment: Option<String>,
    pub reference: Option<serde_json::Value>,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Customer ID must not be empty."))]
    pub customer_id: String,
    #[validate(length(min = 1, message = "Shipping address ID must not be empty."))]
    pub shipping_address_id: String,
    #[validate(length(min = 1, message = "Shipping method code must not be empty."))]
    pub shipping_method_code: String,
    #[validate(length(min = 1, message = "Billing address ID must not be empty."))]
    pub billing_address_id: String,
    #[validate(length(min = 1, message = "Billing method code must not be empty."))]
    pub billing_method_code: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            customer_id: self.customer_id.as_ref().to_owned(),
            shipping_address_id: self.shipping_address_id.as_ref().to_owned(),
            shipping_method_code: self.shipping_method_code.as_ref().to_owned(),
            billing_address_id: self.billing_address_id.as_ref().to_owned(),
            billing_method_code: self.billing_method_code.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::checkout::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a checkout by the provided id
    ///
    /// # Errors
    ///
    /// When could not find checkout or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let checkout = checkout::Entity::find()
            .filter(
                model::query::condition()
                    .eq(checkout::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        checkout.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds checkouts by the provided customer id
    ///
    /// # Errors
    ///
    /// When could not find checkouts or DB query error
    pub async fn find_by_customer_id(
        db: &DatabaseConnection,
        customer_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let checkouts = checkout::Entity::find()
            .filter(
                model::query::condition()
                    .eq(checkout::Column::CustomerId, customer_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(checkouts)
    }

    /// finds checkouts by the provided guest id
    ///
    /// # Errors
    ///
    /// When could not find checkouts or DB query error
    pub async fn find_by_guest_id(
        db: &DatabaseConnection,
        guest_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let checkouts = checkout::Entity::find()
            .filter(
                model::query::condition()
                    .eq(checkout::Column::GuestId, guest_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(checkouts)
    }

    /// Asynchronously creates a checkout and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the checkout into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let checkout = checkout::ActiveModel {
            customer_id: ActiveValue::set(params.customer_id.to_string()),
            guest_id: ActiveValue::set(params.guest_id.to_string()),
            shipping_address_id: ActiveValue::set(params.shipping_address_id.to_string()),
            shipping_method_code: ActiveValue::set(params.shipping_method_code.to_string()),
            billing_address_id: ActiveValue::set(params.billing_address_id.to_string()),
            billing_method_code: ActiveValue::set(params.billing_method_code.to_string()),
            comment: ActiveValue::set(params.comment.clone()),
            reference: ActiveValue::set(params.reference.clone()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(checkout)
    }
}

impl ActiveModel {
    /// Updates the checkout's shipping information
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_shipping(
        mut self,
        db: &DatabaseConnection,
        address_id: String,
        method_code: String,
    ) -> ModelResult<Model> {
        self.shipping_address_id = ActiveValue::set(address_id);
        self.shipping_method_code = ActiveValue::set(method_code);
        Ok(self.update(db).await?)
    }

    /// Updates the checkout's billing information
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_billing(
        mut self,
        db: &DatabaseConnection,
        address_id: String,
        method_code: String,
    ) -> ModelResult<Model> {
        self.billing_address_id = ActiveValue::set(address_id);
        self.billing_method_code = ActiveValue::set(method_code);
        Ok(self.update(db).await?)
    }

    /// Updates the checkout's comment
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_comment(
        mut self,
        db: &DatabaseConnection,
        comment: Option<String>,
    ) -> ModelResult<Model> {
        self.comment = ActiveValue::set(comment);
        Ok(self.update(db).await?)
    }
}
